package cn.tedu.ivos.base.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
@Aspect   //声明该类是一个切面类
public class AspectLog {
    /*
     execution按表达式匹配
     bean--指定对象
     within--指定包
     @annotation--通过注解
     */
    /*
     execution(表达式)
     execution(public JsonResult cn.tedu.ivos.vehicle.controller.VechcleController.selectVehicle(VehicleQuery))
       *匹配，参数..
       execution(public * cn.tedu.ivos.*.controller.*.*(..))
     */
    @Pointcut("execution(public * cn.tedu.ivos.*.controller.*.*(..))")
    public void anyController(){}

    @Before("anyController()")
    public void before(JoinPoint joinPoint){
       requestUrl();
       log.info("前置通知请求的URI");//执行目标方法之前执行
    }
    @After("anyController()")
    public void after(JoinPoint joinPoint){
        requestUrl();
        log.info("后置通知请求的URI"); //执行目标方法后执行
    }
    @AfterThrowing("anyController()")
    public void afterThrowing(JoinPoint joinPoint){
        requestUrl();
        log.info("异常通知请求的URI"); //目标方法执行失败后执行
    }
    @AfterReturning("anyController()")
    public void afterReturning(JoinPoint joinPoint){
        requestUrl();
        log.info("最终通知请求的URI"); //目标方法执行成功后之后
    }

    //打印请求的路径
    private void requestUrl(){
        //通过请求上下文对象获取对应请求信息
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(requestAttributes!=null){
            HttpServletRequest request = requestAttributes.getRequest();
            String requestURI = request.getRequestURI();
            log.info(String.format("请求路径uri: %s",requestURI));
        }
    }
}
